% Splitting matrix into streams with different contexts 
function [main_matrix, streams] = component_cod(QY, levels, m, n, component)
	streams = cell(6, 3);
	min_size1 = ceil(m / 2 ^ levels);
	min_size2 = ceil(n / 2 ^ levels);
    mm = min_size1;
    nn = min_size2;
	I = 0; % number of wavelet matrix
	%contexts for 3 matrix of resolution layer
	contexts = zeros(3, mm * nn);
	
	%Thresholds
	%TH = 64;
	%T = [2 2 2 4 4 4 16 16 16 16 16 16 32 32 32 64 64 64];
    TH = 256;
    T = [1 1 1 1 2 2 2 2 2 3 3 3 8 8 8 8 8 16]; 
    if (component == 2)
        T = [1 1 1 1 2 2 2 2 2 4 4 4 4 4 4 4 4 4];
    end;
    if (component == 3)
        T = [1 1 1 1 2 2 1 2 2 4 4 4 4 4 4 4 4 4];
    end;
	
	while ((mm <= (m / 2)) & (nn <= (n / 2))),
        level_num = ceil((I + 1) / 3);
		contprev = contexts;
        contexts = zeros(3, 4 * mm * nn);
        
        for k = 1:3
            c = get_matrix_corners(mm, nn, k);
            
            [Q, flag, step] = quant_transf(QY(c(1, 1):c(2, 1), c(1, 2):c(2, 2)));
            if (flag == 0)
                QY(c(1, 1):c(2, 1), c(1, 2):c(2, 2)) = Q;
            end;
            
            matrix = QY(c(1, 1):c(2, 1), c(1, 2):c(2, 2));
            [cont, contexts(k, :), data] = Context(matrix, contprev(k, :), TH, m, n);
            tmp = max(max(abs(matrix)));% maximum value of matrix
   
            if tmp~=0
                % Splitting data according to contexts
     			streams{level_num, k} = split(data, cont, T(I + k));
            end;

            if (k == 3)
                contexts(k, :) = round((contexts(1, :) + contexts(2, :))/2);
            end;
        end;
                
    	mm = mm * 2;
    	nn = nn * 2;
  		I = I + 3;
	end;
    main_matrix = QY(1:min_size1, 1:min_size2);
end

function [corners] = get_matrix_corners(width, height, position)
    if (position == 1)
		corners = [1, height + 1; width, height * 2];
        return;
    end;
    if (position == 2)
		corners = [width + 1, 1; width * 2, height];
        return;
    end;
    if (position == 3)
        corners = [width + 1, height + 1; width * 2, height * 2];
        return;
    end;
    corners = [1, 1; width, height];
end
